package org.cweili.vehicle.service

import javax.annotation.Resource
import javax.servlet.http.Cookie

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.cweili.vehicle.entity.Customer
import org.cweili.vehicle.repository.CustomerRepository
import org.cweili.vehicle.repository.ExpenseRepository
import org.cweili.vehicle.repository.JourneyRepository
import org.cweili.vehicle.repository.VehicleRepository
import org.cweili.vehicle.util.Const
import org.directwebremoting.WebContextFactory

import com.alibaba.fastjson.JSONObject

/**
 * 服务基类
 *
 * @author Cweili
 * @version 2013年7月26日 上午12:16:12
 *
 */
abstract class BaseService {

	protected static final Log log = LogFactory.getLog(BaseService)

	@Resource
	protected CustomerRepository customerRepository

	@Resource
	protected VehicleRepository vehicleRepository

	@Resource
	protected JourneyRepository journeyRepository

	@Resource
	protected ExpenseRepository expenseRepository

	protected Customer getCustomer() {
		return (Customer) getSessionAttribute(Const.SESSION_CUSTOMER)
	}

	protected setCookie(name, value, maxAge) {
		def response = WebContextFactory.get().getHttpServletResponse()
		def request = WebContextFactory.get().getHttpServletRequest()
		try {
			def json = value ? URLEncoder.encode(JSONObject.toJSONString(value),
					Const.CHARSET) : ""
			def cookie = new Cookie(name, json)
			cookie.path = request.getContextPath() + "/"
			cookie.maxAge = maxAge
			response.addCookie(cookie)
		} catch (Exception e) {
			log.error(e)
		}
	}

	protected getSessionAttribute(name) {
		def session = WebContextFactory.get().getSession(false)
		if (session) {
			return session.getAttribute(name)
		}
		return null
	}

	protected setSessionAttribute(name, value) {
		def session = WebContextFactory.get().getSession()
		session.setAttribute(name, value)
	}
}
